<template>
  <div class="hideUpload">
    <el-upload
      class="avatar-uploader"
      ref="upload"
      action="#"
      :show-file-list="false"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :auto-upload="false">
      <my-button type="success">上传头像</my-button>
    </el-upload>
  </div>
</template>

<script>
  export default {
    name: "my-upload-base64",
    /** v-model双向绑定 **/
    model: {
      prop: 'value',
      event: 'success'
    },
    props: {
      /** 双向绑定值 **/
      value: [String]
    },
    methods: {
      /** 上传前钩子 **/
      beforeUpload(file){
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG) {
          this.$message.error('上传头像图片只能是 JPG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isJPG && isLt2M;
      },
      onChange(){
        let _this = this;
        let event = event || window.event;
        let file = event.target.files[0];
        let reader = new FileReader();
        //转base64
        reader.onload = function(e) {
          _this.$emit('success',e.target.result)
        }
        reader.readAsDataURL(file);
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
